package com.office.reader;

import java.io.File;
import java.io.FileOutputStream;

import org.apache.poi.hslf.HSLFSlideShow;
import org.apache.poi.hslf.model.Picture;
import org.apache.poi.hslf.model.Slide;
import org.apache.poi.hslf.model.TextRun;
import org.apache.poi.hslf.usermodel.PictureData;
import org.apache.poi.hslf.usermodel.SlideShow;

import com.office.AbstractReader;

public class PptReader extends AbstractReader {
	
	public static void readPpt(String filePath,String imgSavePath){
		getText(filePath, imgSavePath);		
	}

	public static void getText(String filePath,String imgSavePath){
		try{
		SlideShow ppt = new SlideShow(new HSLFSlideShow(filePath));

		Slide[] slides = ppt.getSlides();
		for (int i = 0; i < slides.length; i++) {

			Slide slide = slides[i];
			TextRun[] textRuns = slide.getTextRuns();
			StringBuilder stringBuilder = new StringBuilder();

			for (int j = 0; j < textRuns.length; j++) {
				TextRun textRun = textRuns[j];
				stringBuilder.append(textRun.getText()).append("\n");
			}
			System.out.println(stringBuilder.toString());
		}
		}catch(Exception e){
			e.printStackTrace();
		}
		getPicture(filePath,imgSavePath);
	}

	public static void getPicture(String filePath,String imgSavePath) {
		try {
			// 加载PPT
			HSLFSlideShow _hslf = new HSLFSlideShow(filePath);

			SlideShow _slideShow = new SlideShow(_hslf);

			// 获取PPT文件中的图片数据
			PictureData[] _pictures = _slideShow.getPictureData();

			// 循环读取图片数据
			for (int i = 0; i < _pictures.length; i++) {
				StringBuilder fileName = new StringBuilder(imgSavePath);
				PictureData pic_data = _pictures[i];
				fileName.append(i);
				// 设置格式
				switch (pic_data.getType()) {
				case Picture.JPEG:
					fileName.append(".jpg");
					break;
				case Picture.PNG:
					fileName.append(".png");
					break;
				case Picture.EMF:
					fileName.append(".emf");
					break;
				default:
					fileName.append(".data");
				}
				// 输出文件
				FileOutputStream fileOut = new FileOutputStream(new File(fileName.toString()));
				fileOut.write(pic_data.getData());
				fileOut.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
